package com.alibaba.citrus.cr.sales.plan.facade.service.salesplan;

import com.alibaba.citrus.cr.common.annotation.EpochTransactional;
import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.util.CalculatePercentage;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.common.util.PageUtils;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanLineWriteService;
import com.alibaba.citrus.cr.sales.plan.api.salesplan.SalesPlanQueryService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.BatchUpdateLineStatusRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.EditSalesPlanLineRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.UpdateAdjustCountRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.UpdateTaskCountRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanOutCommonService;
import com.alibaba.citrus.cr.sales.plan.functions.salesplan.SalesPlanLineEntity;
import com.alibaba.citrus.cr.sales.plan.model.SalesPlanLineStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.SalesPlanReportAuditStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesPlanStatusEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanLineRepository;
import com.alibaba.citrus.cr.sales.plan.repository.SalesPlanRepository;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanLineSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.cr.sales.plan.api.statistics.SalesPlanStatService;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QuerySalesPlanLineRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QuerySalesPlanRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SalesPlanDetailBatchQueryRequest;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.SubmitSalesPlanLineRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanCommonService;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.model.dto.WarehouseInfo;
import com.epoch.app.bcorder.sales_plan.bosalesplandetailindex.dto.PageQueryPlanDetailRequest;
import com.epoch.app.bcorder.sales_plan.bosalesplandetailindex.dto.PageQueryPlanDetailResponse;
import com.epoch.app.bcorder.sales_plan.bosalesplandetailindex.service.BoSalesPlanDetailIndexService;
import com.epoch.app.crplatformenhance.domain.customersalescope.model.CustomerSaleScope;
import com.epoch.app.crplatformenhance.sdo.CustomerAddressSDO;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wangyibing
 */
@Component
public class SalesPlanLineWriteServiceImpl implements SalesPlanLineWriteService {

    private final static Logger log= LoggerFactory.getLogger(SalesPlanLineWriteServiceImpl.class);

    private static final String DEFAULT_FROM_SYS = "APP_OTS";

    private static final String DEFAULT_BUSINESS_TYPE = "11";

    private static final String DEFAULT_SC_ITEM_UNIT = "PC";

    @Resource
    private SalesPlanLineRepository salesPlanLineRepository;

    @Resource
    private SalesPlanQueryService salesPlanQueryService;

    @Resource
    private SalesPlanStatService salesPlanStatService;

    @Resource
    private SalesPlanRepository salesPlanRepository;

    @Resource
    private SalesPlanCommonService salesPlanCommonService;

    @Resource
    private BoSalesPlanDetailIndexService boSalesPlanDetailIndexService;

    @Resource
    private SalesPlanOutCommonService salesPlanOutCommonService;

//    @Override
//    @FacadeInvoker
//    public Result<String> createSalesPlanLine(SalesPlanLineSDO salesPlanLineSdo) {
//        SalesPlanLineEntity salesPlanLineEntity = SalesPlanLineEntity.of(salesPlanLineSdo);
//        String lastInsertId = salesPlanLineEntity.doCreate();
//        return Result.success(lastInsertId);
//    }

    @Override
    @FacadeInvoker
    @EpochTransactional(appCode = "bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    public Result<String> batchCreateSalesPlanLine(List<SalesPlanLineSDO> createPlanLineSdoList) {
        if (createPlanLineSdoList == null || createPlanLineSdoList.size() == 0) {
            throw new FacadeException("OTS-02-002-02-15-010");
        }
        SalesPlanSDO planSDO = salesPlanCommonService.checkSalesPlan(createPlanLineSdoList.stream().findFirst().get().getPlanId());

        //planId+客户收收获地址编码+货品编码查询重复数据
        Set<Long> planIdSet = createPlanLineSdoList.stream().map(SalesPlanLineSDO::getPlanId).map(Long::parseLong).collect(Collectors.toSet());
        Set<String> customerAddressSet = createPlanLineSdoList.stream().map(SalesPlanLineSDO::getCustomerAddress).collect(Collectors.toSet());
        Set<String> scItemIdSet = createPlanLineSdoList.stream().map(SalesPlanLineSDO::getScItemId).collect(Collectors.toSet());
        Set<String> customerAddressIdSet = createPlanLineSdoList.stream().map(SalesPlanLineSDO::getCustomerAddressId).filter(StringUtils::isNotBlank).collect(Collectors.toSet());

        SalesPlanDetailBatchQueryRequest salesPlanDetailBatchQueryRequest = new SalesPlanDetailBatchQueryRequest();
        salesPlanDetailBatchQueryRequest.setPlanIds(Lists.newArrayList(planIdSet));
        if (CollectionUtils.isNotEmpty(customerAddressIdSet)) {
            salesPlanDetailBatchQueryRequest.setCustomerAddressIds(Lists.newArrayList(customerAddressIdSet));
        }
        salesPlanDetailBatchQueryRequest.setCustomerAddress(Lists.newArrayList(customerAddressSet));
        salesPlanDetailBatchQueryRequest.setScItemIds(Lists.newArrayList(scItemIdSet));
        List<SalesPlanLineSDO> salesPlanLineSDOS = salesPlanLineRepository.batchQueryDetailByIds(salesPlanDetailBatchQueryRequest);
        if (salesPlanLineSDOS.size() > 0) {
            throw new FacadeException("OTS-02-002-02-15-017");
        }

        //补上计划明细的客户组
        Set<String> customerCodeSet = createPlanLineSdoList.stream().map(SalesPlanLineSDO::getCustomerCode).collect(Collectors.toSet());
        Map<String, CustomerSaleScope> customerSaleScopeMap = salesPlanOutCommonService.getCustomerSaleScopeMap(customerCodeSet);
        for (SalesPlanLineSDO planLineSDO : createPlanLineSdoList) {
            CustomerSaleScope customerSaleScope = customerSaleScopeMap.get(planLineSDO.getCustomerCode());
            if (customerSaleScope!=null) {
                planLineSDO.setParam2(customerSaleScope.getCustomerGroup());
            }
        }

        //获取并设置合同量数据
        salesPlanCommonService.fillContractInfoAndModifySalesPlanDetails(createPlanLineSdoList);
        //创建有总量时，对总量三比均衡
        batchCreateSalesPlanLineListConverter(createPlanLineSdoList,planSDO);

        //补充业中计划明细字段
        enichBcPlanField(createPlanLineSdoList,planSDO);
        return Result.success(salesPlanLineRepository.batchCreateSalesPlanLine(createPlanLineSdoList));
    }

    private void batchCreateSalesPlanLineListConverter(List<SalesPlanLineSDO> salesPlanLineSdoList,SalesPlanSDO planSDO) {
        String planId = salesPlanLineSdoList.stream().findFirst().get().getPlanId();
        if (planSDO == null) {
            QuerySalesPlanRequest querySalesPlanRequest = new QuerySalesPlanRequest();
            querySalesPlanRequest.setId(planId);
            planSDO = salesPlanQueryService.getSalesPlan(querySalesPlanRequest).getResult();
        }
        if (Objects.isNull(planSDO)) {
            throw new FacadeException("OTS-02-002-00-16-001");
        }
        BigDecimal sum = planSDO.getMonthFirstProprtion().add(planSDO.getMonthMiddleProprtion()).add(planSDO.getMonthLastProprtion());
        if (new BigDecimal(100).compareTo(sum) == 0) {
            //月度计划有配置三旬比例均衡
            for (SalesPlanLineSDO salesPlanLineSDO : salesPlanLineSdoList) {
                //创建传总量需要三比均衡
                if (salesPlanLineSDO.getMonthCount() > 0 && Optional.ofNullable(salesPlanLineSDO.getIsBalanced()).orElse(true)) {
                    //月度计划有配置三旬比例均衡
                    //上旬计划量
                    BigDecimal monthFirstProprtion = planSDO.getMonthFirstProprtion();
                    BigDecimal firstCount = monthFirstProprtion.multiply(new BigDecimal(Optional.ofNullable(salesPlanLineSDO.getMonthCount()).orElse(0)));
                    Integer monthFirstCount = firstCount.divide(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).intValue();
                    salesPlanLineSDO.setMonthFirstCount(monthFirstCount);

                    //下旬计划量
                    BigDecimal monthLastProprtion = planSDO.getMonthLastProprtion();
                    BigDecimal LastCount = monthLastProprtion.multiply(new BigDecimal(Optional.ofNullable(salesPlanLineSDO.getMonthCount()).orElse(0)));
                    Integer monthLastCount = LastCount.divide(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).intValue();
                    salesPlanLineSDO.setMonthLastCount(monthLastCount);

                    //中旬计划量
                    Integer monthMiddleCount = salesPlanLineSDO.getMonthCount() - (monthFirstCount + monthLastCount);
                    salesPlanLineSDO.setMonthMiddleCount(monthMiddleCount);
                }

                //常规销售价
                long costInsuranceFreight = Objects.nonNull(salesPlanLineSDO.getCostInsuranceFreight()) ? salesPlanLineSDO.getCostInsuranceFreight() : 0;
                //计算折前计划金额
                long beforeMonthMoney = salesPlanLineSDO.getMonthCount() * costInsuranceFreight;
                salesPlanLineSDO.setBeforeMonthMoney(beforeMonthMoney);
                //计算折后计划金额  折后计划金额=折前计划金额*(1-预估价格折扣率)
                salesPlanLineSDO.calculateMonthMoney(planSDO.getEstimateDiscount());
                //合同差量  合同差量=month_count（计划数量）-month_contract_count（合同量）
                Integer contractDifferenceCount = salesPlanLineSDO.getMonthCount() - salesPlanLineSDO.getMonthContractCount();
                salesPlanLineSDO.setContractDifferenceCount(contractDifferenceCount);
                //合同差金额 合同差金额=计划折前合同金额 -计划折前金额
                long contractDifferenceMoney = salesPlanLineSDO.getBeforeMonthContractMoney() - beforeMonthMoney;
                salesPlanLineSDO.setContractDifferenceMoney(contractDifferenceMoney);
                //计算折前满足度 折前满足度=折前计划金额/折前合同金额
                BigDecimal beforeContractSatisfaction = CalculatePercentage.retainTwo(beforeMonthMoney, salesPlanLineSDO.getBeforeMonthContractMoney());
                salesPlanLineSDO.setBeforeContractSatisfaction(beforeContractSatisfaction);
                //计算折后满足度  折后满足度 = 折后计划金额/折后合同金额
                BigDecimal contractSatisfaction = CalculatePercentage.retainTwo(salesPlanLineSDO.getMonthMoney(), salesPlanLineSDO.getMonthContractMoney());
                salesPlanLineSDO.setContractSatisfaction(contractSatisfaction);

                //到岸价
                long outboundPrice = Objects.nonNull(salesPlanLineSDO.getOutboundPrice()) ? salesPlanLineSDO.getOutboundPrice() : 0;
                //到岸折前金额
                long beforeMonthOutboundMoney = salesPlanLineSDO.getMonthCount() * outboundPrice;
                salesPlanLineSDO.setBeforeMonthOutboundMoney(beforeMonthOutboundMoney);
                //到岸折后金额 到岸折后金额=到岸折前金额*(1-预估价格折扣率)
                salesPlanLineSDO.calculateMonthOutboundMoney(planSDO.getEstimateDiscount());

                //估计折扣率,估计折扣价
                BigDecimal estimatedDiscountRate = planSDO.getEstimateDiscount().multiply(new BigDecimal(100));
                salesPlanLineSDO.setEstimatedDiscountRate(estimatedDiscountRate.intValue());
                BigDecimal discount = BigDecimal.ONE.subtract(planSDO.getEstimateDiscount().multiply(new BigDecimal("0.01").setScale(2, RoundingMode.HALF_UP)));
                BigDecimal estimatedDiscountPrice = new BigDecimal(costInsuranceFreight).multiply(discount).setScale(0, RoundingMode.HALF_UP);
                salesPlanLineSDO.setEstimatedDiscountPrice(estimatedDiscountPrice.longValue());

                //总量不为0时，状态为已完成
                if (0 != Optional.ofNullable(salesPlanLineSDO.getMonthCount()).orElse(0)){
                    salesPlanLineSDO.setStatus(SalesPlanLineStatusEnum.FINISH.getStatus());
                }else {
                    salesPlanLineSDO.setStatus(SalesPlanLineStatusEnum.DRAFT.getStatus());
                }
            }
        }
    }

    /**
     * 补充业中计划明细字段
     * @param createPlanLineSdoList
     * @param planSDO
     */
    private void enichBcPlanField(List<SalesPlanLineSDO> createPlanLineSdoList,SalesPlanSDO planSDO) {
        Set<String> scItemIdSet = createPlanLineSdoList.stream().filter(x->StringUtils.isBlank(x.getScItemCode())).map(SalesPlanLineSDO::getScItemId).collect(Collectors.toSet());
        Set<String> orgSalesOrganizationIdSet = createPlanLineSdoList.stream().map(SalesPlanLineSDO::getOrgSalesOrganizationCode).collect(Collectors.toSet());

        Map<String, ScItemSDO> queryScItemMap = salesPlanOutCommonService.getScItemMapByIds(scItemIdSet, false);
        Map<String, OrganizationSDO> queryOrganizationMap = salesPlanOutCommonService.getOrganizationMapByIds(orgSalesOrganizationIdSet, false);

        String warehouseCode = "-1";
        Map<String, com.epoch.app.crplatformenhance.sdo.OrganizationSDO> orgBusinessUnitMap = salesPlanOutCommonService.getOrganizationMapByOutCode(Sets.newHashSet(planSDO.getOrgBusinessUnitOrgcode()));
        if (MapUtils.isNotEmpty(orgBusinessUnitMap)) {
            com.epoch.app.crplatformenhance.sdo.OrganizationSDO orgBusinessUnit = orgBusinessUnitMap.get(planSDO.getOrgBusinessUnitOrgcode());
            List<WarehouseInfo> sharedWarehouseList = salesPlanOutCommonService.getSharedWarehouseListBySaleOrgId(orgBusinessUnit.getId());
            if (CollectionUtils.isNotEmpty(sharedWarehouseList)) {
                warehouseCode = sharedWarehouseList.get(0).getCode();
            }
        }

        Long maxPlanLineNo = salesPlanLineRepository.queryMaxPlanLineNo(planSDO.getId());

        for (SalesPlanLineSDO sdo : createPlanLineSdoList) {
            maxPlanLineNo++;
            sdo.setPlanNo(planSDO.getPlanNo());
            sdo.setPlanDetailNo(String.valueOf(maxPlanLineNo));
            sdo.setOrgEnterpriseGroupCode(planSDO.getOrgEnterpriseGroupCode());
            sdo.setOrgRegionCode(planSDO.getOrgRegionCode());
            sdo.setOrgProvinceCode(planSDO.getOrgProvinceCode());
            sdo.setBizUnitCode(planSDO.getOrgBusinessUnitOrgcode());

            sdo.setWarehouseCode(warehouseCode);

            if (StringUtils.isNotBlank(sdo.getOrgSalesOrganizationCode()) && MapUtils.isNotEmpty(queryOrganizationMap)) {
                OrganizationSDO organizationSDO = queryOrganizationMap.get(sdo.getOrgSalesOrganizationCode());
                sdo.setOrgSalesOrganizationOrgcode(organizationSDO!=null?organizationSDO.getCode():null);
            }

            if (StringUtils.isBlank(sdo.getScItemCode()) && MapUtils.isNotEmpty(queryScItemMap)) {
                ScItemSDO scItemSDO = queryScItemMap.get(sdo.getScItemId());
                sdo.setScItemCode(scItemSDO!=null?scItemSDO.getOuterId():null);
                sdo.setScItemBrandId(scItemSDO!=null?scItemSDO.getBrandId():null);
            }
            sdo.setScItemGroup(StringUtils.isNoneBlank(sdo.getScItemGroup())?sdo.getScItemGroup():DEFAULT_BUSINESS_TYPE);
            sdo.setBasicUnit(StringUtils.isNoneBlank(sdo.getBasicUnit())?sdo.getBasicUnit():DEFAULT_SC_ITEM_UNIT);

            sdo.setBusinessType(DEFAULT_BUSINESS_TYPE);
            sdo.setFromSys(DEFAULT_FROM_SYS);

            sdo.setPlanTime(DateUtils.toDateStr(Long.parseLong(planSDO.getPlanTime()),DateUtils.PATTEN_YM_PLAIN));
        }
    }

    /**
     * 失焦保存
     */
    @Override
    @FacadeInvoker
    public Result<SalesPlanLineSDO> editSalesPlanLine(EditSalesPlanLineRequest editSalesPlanRequest) {
        QuerySalesPlanLineRequest querySalesPlanLineRequest = new QuerySalesPlanLineRequest();
        querySalesPlanLineRequest.setId(editSalesPlanRequest.getId());
        SalesPlanLineSDO salesPlanLineSDO = salesPlanLineRepository.querySalesPlanLine(querySalesPlanLineRequest);
        if (null == salesPlanLineSDO) {
            return null;
        }
        String planId = salesPlanLineSDO.getPlanId();
        SalesPlanLineSDO editSdo = editSalesPlanRequestConverter(salesPlanLineSDO, editSalesPlanRequest);
        //总量为0明细状态变更为草稿
        if (0 == editSdo.getMonthCount()) {
            editSdo.setStatus(SalesPlanLineStatusEnum.DRAFT.getStatus());
        } else {
            editSdo.setStatus(SalesPlanLineStatusEnum.FINISH.getStatus());
        }
        SalesPlanLineEntity salesPlanLineEntity = SalesPlanLineEntity.of(editSdo);
        Integer count = salesPlanLineEntity.doEdit();

//        StopWatch stopWatch = new StopWatch();
//        stopWatch.start();
//        //触发汇总更新
//        try {
//            salesPlanStatService.planCollect(planId);
//        } catch (Exception e) {
//            log.error("修改月度计划明细,触发汇总更新失败:"+e.getMessage());
//            e.printStackTrace();
//        }
//        stopWatch.stop();
//        System.out.println("-----------------------------"+stopWatch.getTotalTimeMillis());

        if (count == 1) {
            return Result.success(salesPlanLineRepository.querySalesPlanLine(querySalesPlanLineRequest));
        }
        return null;
    }

    private SalesPlanLineSDO editSalesPlanRequestConverter(SalesPlanLineSDO originSdo, EditSalesPlanLineRequest editRequest) {
        // 构建失焦保存的sdo
        SalesPlanLineSDO editSdo = SalesPlanLineSDO.builder().build();
        BeanUtils.copyProperties(originSdo, editSdo);
        String planId = originSdo.getPlanId();
        QuerySalesPlanRequest querySalesPlanRequest = new QuerySalesPlanRequest();
        querySalesPlanRequest.setId(planId);
        Result<SalesPlanSDO> salesPlan = salesPlanQueryService.getSalesPlan(querySalesPlanRequest);
        log.info("编辑月度计划明细 失焦保存 {} ", JSONObject.toJSONString(salesPlan));
        if (salesPlan.getResult() != null && salesPlan.getResult().getAuditStatus() != null) {
            if (SalesPlanReportAuditStatusEnum.UNDER_REVIEW.getCode().intValue() == salesPlan.getResult().getAuditStatus().intValue()) {
                throw new FacadeException("OTS-02-002-02-15-036");
            }
        }

        SalesPlanSDO salesPlanSDO = salesPlan.getResult();
        if (Optional.ofNullable(editRequest.getIsBalanced()).orElse(true)) {
            //传总量,需要按照三旬比例均衡计算
            if (Objects.nonNull(salesPlanSDO)) {
                BigDecimal sum = salesPlanSDO.getMonthFirstProprtion().add(salesPlanSDO.getMonthMiddleProprtion()).add(salesPlanSDO.getMonthLastProprtion());
                if (new BigDecimal(100).compareTo(sum) == 0) {
                    //月度计划有配置三旬比例均衡
                    //计划量
                    editSdo.setMonthCount(Optional.ofNullable(editRequest.getMonthCount()).orElse(0));
                    //上旬计划量
                    BigDecimal monthFirstProprtion = salesPlanSDO.getMonthFirstProprtion();
                    BigDecimal firstCount = monthFirstProprtion.multiply(new BigDecimal(Optional.ofNullable(editRequest.getMonthCount()).orElse(0)));
                    Integer monthFirstCount = firstCount.divide(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).intValue();
                    editSdo.setMonthFirstCount(monthFirstCount);

                    //下旬计划量
                    BigDecimal monthLastProprtion = salesPlanSDO.getMonthLastProprtion();
                    BigDecimal LastCount = monthLastProprtion.multiply(new BigDecimal(Optional.ofNullable(editRequest.getMonthCount()).orElse(0)));
                    Integer monthLastCount = LastCount.divide(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).intValue();
                    editSdo.setMonthLastCount(monthLastCount);

                    //中旬计划量
                    Integer monthMiddleCount = Optional.ofNullable(editRequest.getMonthCount()).orElse(0) - (monthFirstCount + monthLastCount);
                    editSdo.setMonthMiddleCount(monthMiddleCount);
                }
            }
        } else {
            if (Optional.ofNullable(editRequest.getMonthCount()).orElse(0) != Optional.ofNullable(editRequest.getMonthFirstCount()).orElse(0) + Optional.ofNullable(editRequest.getMonthMiddleCount()).orElse(0) + Optional.ofNullable(editRequest.getMonthLastCount()).orElse(0)) {
                //不相等,抛异常
                throw new FacadeException("OTS-02-002-02-15-009");
            } else {
                //计划量
                editSdo.setMonthCount(Optional.ofNullable(editRequest.getMonthCount()).orElse(0));
                //上旬计划量
                editSdo.setMonthFirstCount(Optional.ofNullable(editRequest.getMonthFirstCount()).orElse(0));
                //中旬计划量
                editSdo.setMonthMiddleCount(Optional.ofNullable(editRequest.getMonthMiddleCount()).orElse(0));
                //下旬计划量
                editSdo.setMonthLastCount(Optional.ofNullable(editRequest.getMonthLastCount()).orElse(0));
            }
        }
        //计算折前计划金额
        long costInsuranceFreight = Objects.nonNull(originSdo.getCostInsuranceFreight()) ? originSdo.getCostInsuranceFreight() : 0;
        long beforeMonthMoney = Optional.ofNullable(editRequest.getMonthCount()).orElse(0) * costInsuranceFreight;
        editSdo.setBeforeMonthMoney(beforeMonthMoney);
        //计算折后计划金额  折后计划金额=折前计划金额*(1-预估价格折扣率)
        editSdo.calculateMonthMoney(salesPlanSDO.getEstimateDiscount());
        //合同差量  合同差量=month_count（计划数量）-month_contract_count（合同量）
        Integer contractDifferenceCount = Optional.ofNullable(editRequest.getMonthCount()).orElse(0) - originSdo.getMonthContractCount();
        editSdo.setContractDifferenceCount(contractDifferenceCount);
        //合同差金额 合同差金额=计划折前合同金额 -计划折前金额
        long contractDifferenceMoney = originSdo.getBeforeMonthContractMoney() - beforeMonthMoney;
        editSdo.setContractDifferenceMoney(contractDifferenceMoney);
        //计算折前满足度 折前满足度=折前计划金额/折前合同金额
        BigDecimal beforeContractSatisfaction = CalculatePercentage.retainTwo(beforeMonthMoney, originSdo.getBeforeMonthContractMoney());
        editSdo.setBeforeContractSatisfaction(beforeContractSatisfaction);
        //计算折后满足度  折后满足度 = 折后计划金额/折后合同金额
        BigDecimal contractSatisfaction = CalculatePercentage.retainTwo(editSdo.getMonthMoney(), originSdo.getMonthContractMoney());
        editSdo.setContractSatisfaction(contractSatisfaction);
        //修改滚动量
        editSdo.setM1RollingPlanCount(Optional.ofNullable(editRequest.getM1RollingPlanCount()).orElse(0));
        editSdo.setM2RollingPlanCount(Optional.ofNullable(editRequest.getM2RollingPlanCount()).orElse(0));
        editSdo.setM3RollingPlanCount(Optional.ofNullable(editRequest.getM3RollingPlanCount()).orElse(0));
        editSdo.setGmtModified(new Date());
        //到岸折前金额
        long outboundPrice = Objects.nonNull(originSdo.getOutboundPrice()) ? originSdo.getOutboundPrice() : 0;
        long beforeMonthOutboundMoney = Optional.ofNullable(editRequest.getMonthCount()).orElse(0) * outboundPrice;
        editSdo.setBeforeMonthOutboundMoney(beforeMonthOutboundMoney);
        //到岸折后金额 到岸折后金额=到岸折前金额*(1-预估价格折扣率)
        editSdo.calculateMonthOutboundMoney(salesPlanSDO.getEstimateDiscount());
        return editSdo;
    }

    /**
     * 修改任务量
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> updateTaskCount(UpdateTaskCountRequest updateTaskCountRequest) {
        QuerySalesPlanLineRequest querySalesPlanLineRequest = new QuerySalesPlanLineRequest();
        querySalesPlanLineRequest.setId(updateTaskCountRequest.getId());
        try {
            SalesPlanLineSDO sdo = salesPlanLineRepository.querySalesPlanLine(querySalesPlanLineRequest);
            SalesPlanLineSDO salesPlanLineSdo = updateTaskCountRequestConverter(sdo, updateTaskCountRequest);
            SalesPlanLineEntity salesPlanLineEntity = SalesPlanLineEntity.of(salesPlanLineSdo);
            Integer count = salesPlanLineEntity.doEdit();
            if (count > 0) {
                return Result.success(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(false);
    }

    private SalesPlanLineSDO updateTaskCountRequestConverter(SalesPlanLineSDO sdo, UpdateTaskCountRequest updateTaskCountRequest) {
        sdo.setTaskCount(updateTaskCountRequest.getTaskCount());
        sdo.setMonthFirstTaskCount(updateTaskCountRequest.getMonthFirstTaskCount());
        sdo.setMonthMiddleTaskCount(updateTaskCountRequest.getMonthMiddleTaskCount());
        sdo.setMonthLastTaskCount(updateTaskCountRequest.getMonthLastTaskCount());
        if (sdo.getTaskCount() != null && sdo.getCostInsuranceFreight() != null) {
            //sdo.setTaskMoney(sdo.getTaskCount() * sdo.getCostInsuranceFreight());
        }
        return sdo;
    }

    @Override
    @FacadeInvoker
    public Result<Integer> updateAdjustCount(UpdateAdjustCountRequest updateAdjustCountRequest) {
        QuerySalesPlanLineRequest querySalesPlanLineRequest = new QuerySalesPlanLineRequest();
        querySalesPlanLineRequest.setId(updateAdjustCountRequest.getId());
        SalesPlanLineSDO sdo = salesPlanLineRepository.querySalesPlanLine(querySalesPlanLineRequest);
        QuerySalesPlanRequest querySalesPlanRequest = new QuerySalesPlanRequest();
        querySalesPlanRequest.setId(sdo.getPlanId());
        SalesPlanSDO salesPlanSDO = salesPlanQueryService.getSalesPlan(querySalesPlanRequest).getResult();
        if (Objects.isNull(salesPlanSDO)) {
            throw new FacadeException("OTS-02-002-00-16-001");
        }
        updateAdjustCountRequestConverter(sdo, updateAdjustCountRequest, salesPlanSDO);
        SalesPlanLineEntity salesPlanLineEntity = SalesPlanLineEntity.of(sdo);
        return Result.success(salesPlanLineEntity.doEdit());
    }

    private void updateAdjustCountRequestConverter(SalesPlanLineSDO sdo, UpdateAdjustCountRequest updateAdjustCountRequest, SalesPlanSDO salesPlanSDO) {
        sdo.setAdjustCount(updateAdjustCountRequest.getAdjustCount());
        sdo.setAdjustMoney(updateAdjustCountRequest.getAdjustMoney());
        sdo.setBeforeAdjustMoney(updateAdjustCountRequest.getBeforeAdjustMoney());
        sdo.setMonthFirstAdjustCount(updateAdjustCountRequest.getMonthFirstAdjustCount());
        sdo.setMonthMiddleAdjustCount(updateAdjustCountRequest.getMonthMiddleAdjustCount());
        sdo.setMonthLastAdjustCount(updateAdjustCountRequest.getMonthLastAdjustCount());
//        sdo.setMonthFirstAdjustReturnCount(updateAdjustCountRequest.getMonthFirstAdjustReturnCount());
//        sdo.setMonthMiddleAdjustReturnCount(updateAdjustCountRequest.getMonthMiddleAdjustReturnCount());
//        sdo.setMonthLastAdjustReturnCount(updateAdjustCountRequest.getMonthLastAdjustReturnCount());
        sdo.calculateAdjustMoney(salesPlanSDO.getEstimateDiscount());
        sdo.setGmtModified(new Date());
    }

    @Override
    @FacadeInvoker
    public Result<String> batchImportCreateSalesPlanLine(List<SalesPlanLineSDO> createPlanLineSdoList) {
        if (createPlanLineSdoList == null || CollectionUtils.isEmpty(createPlanLineSdoList)) {
            throw new FacadeException("OTS-02-002-02-15-010");
        }
        SalesPlanSDO planSDO = salesPlanCommonService.checkSalesPlan(createPlanLineSdoList.stream().findFirst().get().getPlanId());

        //planId+客户收收获地址编码+货品编码查询重复数据，重复则更新，否则新增
        Set<Long> planIdSet = createPlanLineSdoList.stream().map(SalesPlanLineSDO::getPlanId).map(num -> Long.parseLong(num.trim())).collect(Collectors.toSet());
        Set<String> scItemIdSet = createPlanLineSdoList.stream().map(SalesPlanLineSDO::getScItemId).collect(Collectors.toSet());
        Set<String> customerAddressSet = createPlanLineSdoList.stream().map(SalesPlanLineSDO::getCustomerAddress).collect(Collectors.toSet());
        Set<String> customerAddressIdSet = createPlanLineSdoList.stream().map(SalesPlanLineSDO::getCustomerAddressId).filter(StringUtils::isNotBlank).collect(Collectors.toSet());

        SalesPlanDetailBatchQueryRequest salesPlanDetailBatchQueryRequest = new SalesPlanDetailBatchQueryRequest();
        salesPlanDetailBatchQueryRequest.setPlanIds(Lists.newArrayList(planIdSet));
        salesPlanDetailBatchQueryRequest.setScItemIds(Lists.newArrayList(scItemIdSet));
        salesPlanDetailBatchQueryRequest.setCustomerAddress(Lists.newArrayList(customerAddressSet));
        if (CollectionUtils.isNotEmpty(customerAddressIdSet)) {
            salesPlanDetailBatchQueryRequest.setCustomerAddressIds(Lists.newArrayList(customerAddressIdSet));
        }
        List<SalesPlanLineSDO> querySalesPlanLineList = salesPlanLineRepository.batchQueryDetailByIds(salesPlanDetailBatchQueryRequest);
        log.info("SalesPlanLineWriteServiceImpl_batchImportCreateSalesPlanLine_batchQueryDetailByIds_request={},result_size={}",JSONObject.toJSONString(salesPlanDetailBatchQueryRequest),querySalesPlanLineList.size());
        Map<String, SalesPlanLineSDO> querySalesPlanLineMap = querySalesPlanLineList.stream().collect(Collectors.toMap(x -> { return fetchImportPlanLineKey(x); }, a -> a, (a, b) -> a));

        Set<String> customerCodeSet = createPlanLineSdoList.stream().map(SalesPlanLineSDO::getCustomerCode).collect(Collectors.toSet());
        Map<String, CustomerSaleScope> customerSaleScopeMap = salesPlanOutCommonService.getCustomerSaleScopeMap(customerCodeSet);

        //新增
        List<SalesPlanLineSDO> batchCreateRequestList = new ArrayList<>();
        //修改
        List<SalesPlanLineSDO> batchEditRequestList = new ArrayList<>();

        //过滤出新增还是修改
        for (SalesPlanLineSDO planLineSDO : createPlanLineSdoList) {
            String key = fetchImportPlanLineKey(planLineSDO);
            SalesPlanLineSDO querySalesPlanLineSDO = querySalesPlanLineMap.get(key);

            //补上计划明细的客户组
            CustomerSaleScope customerSaleScope = customerSaleScopeMap.get(planLineSDO.getCustomerCode());
            if (customerSaleScope!=null) {
                planLineSDO.setParam2(customerSaleScope.getCustomerGroup());
            }

            planLineSDO.setStatus(SalesPlanLineStatusEnum.FINISH.getStatus());
            if (Objects.isNull(querySalesPlanLineSDO)) {
                batchCreateRequestList.add(planLineSDO);
            } else {
                Integer monthCount = Optional.ofNullable(planLineSDO.getMonthCount()).orElse(0);
                Integer monthFirstCount = Optional.ofNullable(planLineSDO.getMonthFirstCount()).orElse(0);
                Integer monthMiddleCount = Optional.ofNullable(planLineSDO.getMonthMiddleCount()).orElse(0);
                Integer monthLastCount = Optional.ofNullable(planLineSDO.getMonthLastCount()).orElse(0);
                Integer m1RollingPlanCount = Optional.ofNullable(planLineSDO.getM1RollingPlanCount()).orElse(0);
                Integer m2RollingPlanCount = Optional.ofNullable(planLineSDO.getM2RollingPlanCount()).orElse(0);
                Integer m3RollingPlanCount = Optional.ofNullable(planLineSDO.getM3RollingPlanCount()).orElse(0);
                Boolean isBalanced = Optional.ofNullable(planLineSDO.getIsBalanced()).orElse(true);
                String scItemGroup = planLineSDO.getScItemGroup();
                String scItemLeafCategoryId = planLineSDO.getScItemLeafCategoryId();
                String scItemRootCategoryId = planLineSDO.getScItemRootCategoryId();
                Long costInsuranceFreight = planLineSDO.getCostInsuranceFreight();
                String basicUnit = planLineSDO.getBasicUnit();
                Long outboundPrice = planLineSDO.getOutboundPrice();

                BeanUtils.copyProperties(querySalesPlanLineSDO, planLineSDO);
                planLineSDO.setScItemGroup(scItemGroup);
                planLineSDO.setScItemLeafCategoryId(scItemLeafCategoryId);
                planLineSDO.setScItemRootCategoryId(scItemRootCategoryId);
                planLineSDO.setCostInsuranceFreight(costInsuranceFreight);
                planLineSDO.setBasicUnit(basicUnit);
                planLineSDO.setOutboundPrice(outboundPrice);
                planLineSDO.setMonthCount(monthCount);
                planLineSDO.setMonthFirstCount(monthFirstCount);
                planLineSDO.setMonthMiddleCount(monthMiddleCount);
                planLineSDO.setMonthLastCount(monthLastCount);
                planLineSDO.setM1RollingPlanCount(m1RollingPlanCount);
                planLineSDO.setM2RollingPlanCount(m2RollingPlanCount);
                planLineSDO.setM3RollingPlanCount(m3RollingPlanCount);
                planLineSDO.setIsBalanced(isBalanced);
                batchEditRequestList.add(planLineSDO);
            }
        }

        Integer count = 0;
        if (batchCreateRequestList.size() > 0) {
            //新增获取并设置合同量数据
            salesPlanCommonService.fillContractInfoAndModifySalesPlanDetails(batchCreateRequestList);
            //创建有总量时，对总量三比均衡
            batchCreateSalesPlanLineListConverter(batchCreateRequestList,planSDO);
            //补充业中计划明细字段
            enichBcPlanField(createPlanLineSdoList,planSDO);
            String batchCreateCount = salesPlanLineRepository.batchCreateSalesPlanLine(batchCreateRequestList);
            count += Integer.parseInt(batchCreateCount);
        }

        if (batchEditRequestList.size() > 0) {
            //修改获取并设置合同量数据
            salesPlanCommonService.fillContractInfoAndModifySalesPlanDetails(batchEditRequestList);
            //创建有总量时，对总量三比均衡
            batchCreateSalesPlanLineListConverter(batchEditRequestList,planSDO);
            for (SalesPlanLineSDO salesPlanLineSDO : batchEditRequestList) {
                Integer editCount = salesPlanLineRepository.edit(salesPlanLineSDO);
                count += editCount;
            }
        }
        return Result.success(count.toString());
    }

    private String fetchImportPlanLineKey(SalesPlanLineSDO sdo){
        StringBuilder builder = new StringBuilder(sdo.getPlanId());
        if (StringUtils.isNotBlank(sdo.getCustomerAddressId())) {
            builder.append(sdo.getCustomerAddressId());
        }
        builder.append(sdo.getCustomerAddress()).append(sdo.getScItemId());
        return builder.toString();
    }

    /**
     * 提交保存的数据
     *
     * @param request： 筛选要被提交的计划明细数据（客户、货品）
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> submitSalesPlanLine(SubmitSalesPlanLineRequest request) {
        //批量查询月度计划明细，判断上中下旬计划量是否填报完成，更新状态
        List<Long> ids = request.getIds();
        ids.forEach(id -> {
            QuerySalesPlanLineRequest querySalesPlanLineRequest = new QuerySalesPlanLineRequest();
            querySalesPlanLineRequest.setId(id);
            SalesPlanLineSDO sdo = salesPlanLineRepository.querySalesPlanLine(querySalesPlanLineRequest);
            Boolean bool = checkStatus(sdo);
          /*  if (bool && !Objects.equals(sdo.getStatus(), SalesPlanLineStatusEnum.FINISH_FILL.getStatus())) {
                //sdo.setStatus(SalesPlanLineStatusEnum.FINISH_FILL.getStatus());
                SalesPlanLineEntity salesPlanLineEntity = SalesPlanLineEntity.of(sdo);
                salesPlanLineEntity.doEdit();
                SalesPlanStatAbilityRequest statAbilityRequest = SalesPlanStatRequestConverter.submitSalesPlanLineConverter(sdo);
                Boolean aBoolean = salesPlanStatAbility.salesPlanStat(statAbilityRequest);
            }*/
        });
        return Result.success(true);
    }

//    @Nullable
//    private Result<Boolean> getSubmitResult(PageQueryPlanLineRequest pageQueryPlanLineRequest) {
//        int size = pageQueryPlanLineRequest.getSize();
//        int totalPage = getPageCount(size, salesPlanLineRepository.pageQuerySalesPlanLineList(pageQueryPlanLineRequest).getTotal());
//        AtomicInteger draftCount = new AtomicInteger();
//        List<SalesPlanLineSDO> toSubmitList = new ArrayList<>();
//        // 检查每页的数据
//        for (int page = 1; page <= totalPage; page++) {
//            pageQueryPlanLineRequest.setPage(page);
//            List<SalesPlanLineSDO> sdos = salesPlanLineRepository.pageQuerySalesPlanLineList(pageQueryPlanLineRequest).getContent();
//            for (SalesPlanLineSDO sdo : sdos) {
//                if (sdo.getStatus().equals(SalesPlanLineStatusEnum.DRAFT.getStatus())) {
//                    draftCount.getAndIncrement();
//                    break;
//                }
//                toSubmitList.add(sdo);
//            }
//            //存在未完成的明细，不再循环
//            if (draftCount.get() > 0) {
//                break;
//            }
//        }
//        if (draftCount.get() > 0) {
//            return Result.failure("", "存在未完成的明细,无法保存");
//        }
//       /* List<SalesPlanLineSDO> submitStatList = toSubmitList.stream().filter(sdo -> sdo.getStatus().equals(SalesPlanLineStatusEnum.TO_BE_UPDATED.getStatus()))
//                .peek(sdo -> sdo.setStatus(SalesPlanLineStatusEnum.FINISH_FILL.getStatus())).collect(Collectors.toList());*/
//        List<SalesPlanLineSDO> submitStatList = new ArrayList<>();
//        if (CollectionUtils.isNotEmpty(submitStatList)) {
//            // 批量更新
//            Integer count = salesPlanLineRepository.batchUpdateLineStatus(submitStatList);
//            // 触发汇总
//            SalesPlanStatAbilityRequest statAbilityRequest = SalesPlanStatRequestConverter.submitSalesPlanLineListConverter(submitStatList);
//            salesPlanStatAbility.salesPlanStat(statAbilityRequest);
//            return Result.success(submitStatList.size() == count);
//        }
//        return Result.success(true);
//    }


    @Override
    @EpochTransactional(appCode = "bc_order", dataSourceCode = "cr_ots", dataSourceType = "app")
    @FacadeInvoker
    public Result<Integer> batchUpdateLineStatus(BatchUpdateLineStatusRequest batchUpdateLineStatusRequest) {
        List<SalesPlanLineSDO> queryLineList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(batchUpdateLineStatusRequest.getSalesPlanLineSDOList())){
            SalesPlanDetailBatchQueryRequest queryRequest = new SalesPlanDetailBatchQueryRequest();
            List<Long> ids = batchUpdateLineStatusRequest.getSalesPlanLineSDOList().stream().map(x->x.getId()).collect(Collectors.toList());
            queryRequest.setIds(ids);
            queryLineList = salesPlanLineRepository.batchQueryDetailByIds(queryRequest);
        }else{
            //支持按条件查询批量删除
            if(StringUtils.isBlank(batchUpdateLineStatusRequest.getPlanId())){
                throw new FacadeException("OTS-02-004-01-15-001");
            }
            int limit = 1000;
            PageQueryPlanDetailRequest queryRequest = pageQueryPlanDetailRequestConverter(batchUpdateLineStatusRequest);
            queryRequest.setStart(0);
            queryRequest.setLimit(limit);
            PageQueryPlanDetailResponse response = boSalesPlanDetailIndexService.pageQueryPlanDetail(queryRequest);
            List<SalesPlanLineSDO> lines = Nullable.stream(response.getResult()).map(x->{
                SalesPlanLineSDO sdo = new SalesPlanLineSDO();
                BeanUtils.copyProperties(x,sdo);
                sdo.setPlanId(String.valueOf(x.getPlanId()));
                return sdo;
            }).collect(Collectors.toList());
            queryLineList.addAll(lines);
            log.info("SalesPlanLineWriteServiceImpl_batchUpdateLineStatus_queryESSalesPlanLine_getTotal={}",response.getTotal());

            int totalPage = PageUtils.getTotalPage(response.getTotal(),limit);
            for (int pageNo = 1; pageNo < totalPage; pageNo++) {
                queryRequest.setStart(pageNo*limit);
                queryRequest.setLimit(limit);
                PageQueryPlanDetailResponse response2 = boSalesPlanDetailIndexService.pageQueryPlanDetail(queryRequest);
                List<SalesPlanLineSDO> lines2 = Nullable.stream(response2.getResult()).map(x->{
                    SalesPlanLineSDO sdo = new SalesPlanLineSDO();
                    BeanUtils.copyProperties(x,sdo);
                    sdo.setPlanId(String.valueOf(x.getPlanId()));
                    return sdo;
                }).collect(Collectors.toList());
                queryLineList.addAll(lines2);
            }
        }
        if (queryLineList.size() <= 0) {
            throw new FacadeException("OTS-02-002-00-16-004");
        }
        // 只删除‘可删除’的明细行
        List<SalesPlanLineSDO> deleteLineList = queryLineList.stream().filter(x->!"1".equals(x.getParam1())).collect(Collectors.toList());
        log.info("SalesPlanLineWriteServiceImpl_batchUpdateLineStatus_querySalesPlanLine_size={}, allowDeleteSalesPlanLine_size{}",queryLineList.size(),deleteLineList.size());
        if (deleteLineList.size() <= 0) {
            throw new FacadeException("OTS-02-002-02-15-037");
        }

        SalesPlanLineSDO salesPlanLineSDO = deleteLineList.stream().findFirst().get();
        String planId = salesPlanLineSDO.getPlanId();
        QuerySalesPlanRequest request = new QuerySalesPlanRequest();
        request.setId(planId);
        SalesPlanSDO salesPlanSDO = salesPlanRepository.load(request);
        if (salesPlanSDO == null) {
            throw new FacadeException("OTS-02-002-00-16-001");
        }
        if (!SalesPlanStatusEnum.TO_BE_LOCKED.getCode().equals(salesPlanSDO.getStatus())
            && !SalesPlanStatusEnum.TO_BE_SYNC.getCode().equals(salesPlanSDO.getStatus())) {
            //计划不是待锁定和待同步，不允许删除
            throw new FacadeException("OTS-02-002-00-16-005");
        }
        //是否汇总
        Boolean isSummary = false;
        for (SalesPlanLineSDO lineSDO : deleteLineList) {
            if (SalesPlanLineStatusEnum.FINISH.getStatus().equals(lineSDO.getStatus())) {
                isSummary = true;
                break;
            }
        }
        Integer count = 0;
        if(deleteLineList.size()>500){
            int size = 500;
            int totalPage = PageUtils.getTotalPage(deleteLineList.size(),size);
            for (int i = 0; i < totalPage; i++) {
                int start = i * size;
                int end = i+1 == totalPage ? deleteLineList.size(): start + size;
                List<SalesPlanLineSDO> list = deleteLineList.subList(start, end);
                Integer line = salesPlanLineRepository.batchUpdateLineStatus(list);
                count = count+line;
            }
        }else{
            count = salesPlanLineRepository.batchUpdateLineStatus(deleteLineList);
        }
        if (count > 0) {
            if (isSummary) {
                //明细存在已完成状态数据,触发汇总
                salesPlanStatService.planCollect(planId);
            }
        }

        // 计划明细删除行数不等于查询行数，提示操作部分成功
        if (count != queryLineList.size()) {
            return Result.success(count, ErrorMessage.code("OTS-02-002-02-15-038",count).getDisplayErrorMessage());
        }

        return Result.success(count);
    }

    private PageQueryPlanDetailRequest pageQueryPlanDetailRequestConverter(BatchUpdateLineStatusRequest batchUpdateLineStatusRequst){
        PageQueryPlanDetailRequest queryRequest = new PageQueryPlanDetailRequest();
        queryRequest.setPlanId(Long.valueOf(batchUpdateLineStatusRequst.getPlanId()));
        queryRequest.setStatus(batchUpdateLineStatusRequst.getStatus());

        List<String> scItemIdList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(batchUpdateLineStatusRequst.getScItemIdList())) {
            scItemIdList.addAll(batchUpdateLineStatusRequst.getScItemIdList());
        }
        if (StringUtils.isNotBlank(batchUpdateLineStatusRequst.getScItemCode())) {
            Map<String, ScItemSDO> scItemMap = salesPlanOutCommonService.getScItemMapByOutId(Sets.newHashSet(batchUpdateLineStatusRequst.getScItemCode()));
            if(scItemMap != null){
                scItemIdList.addAll(scItemMap.values().stream().map(x->x.getScItemId()).collect(Collectors.toList()));
            }else{
                scItemIdList.add("-1");
            }
        }
        if(CollectionUtils.isNotEmpty(scItemIdList)){
            queryRequest.setScItemIdList(scItemIdList);
        }

        queryRequest.setScItemLeafCategoryIdList(batchUpdateLineStatusRequst.getScItemLeafCategoryIdList());
        queryRequest.setCustomerCodeList(StringUtils.isNotBlank(batchUpdateLineStatusRequst.getCustomerCode())?Lists.newArrayList(batchUpdateLineStatusRequst.getCustomerCode()):null);
        queryRequest.setCustomerAddress(batchUpdateLineStatusRequst.getCustomerAddress());
        queryRequest.setCustomerAddressList(batchUpdateLineStatusRequst.getCustomerAddresss());
        queryRequest.setManageEmployeeIdList(StringUtils.isNotBlank(batchUpdateLineStatusRequst.getManageEmployeeId())?Lists.newArrayList(batchUpdateLineStatusRequst.getManageEmployeeId()):null);
        queryRequest.setAppletSubmission(batchUpdateLineStatusRequst.getAppletSubmission());
        queryRequest.setContractDifferenceMoneyStamp(batchUpdateLineStatusRequst.getContractDifferenceMoneyStamp());
        SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(batchUpdateLineStatusRequst.getBizType());
        if(byOrganizationType == null){
            QuerySalesPlanRequest querySalesPlanRequest = new QuerySalesPlanRequest();
            querySalesPlanRequest.setId(batchUpdateLineStatusRequst.getPlanId());
            Result<SalesPlanSDO> result = salesPlanQueryService.getSalesPlan(querySalesPlanRequest);
            if (!result.isSuccess() || null == result.getResult()) {
                throw new FacadeException("OTS-02-002-00-16-001");
            }
            String orgBusinessUnitCode = result.getResult().getOrgBusinessUnitCode();
            if (StringUtil.isBlank(orgBusinessUnitCode)) {
                log.info("subTotalSalesPlanDetail月度计划{}缺少业务单位编码", batchUpdateLineStatusRequst.getPlanId());
                throw new FacadeException("OTS-02-002-00-16-002");
            }
            queryRequest.setOrgBusinessUnitCode(orgBusinessUnitCode);
        }else{
            switch (byOrganizationType) {
                case SALESMAN:
                    queryRequest.setManageEmployeeIdList(Lists.newArrayList(batchUpdateLineStatusRequst.getBizId()));
                    break;
                case SALES_DEPARTMENT:
                    queryRequest.setOrgSalesDepartmentCode(batchUpdateLineStatusRequst.getBizId());
                    break;
                case SALES_CHANNEL:
                    queryRequest.setOrgSalesChannelCode(batchUpdateLineStatusRequst.getBizId());
                    break;
                case SALES_ORGANIZATION:
                    queryRequest.setOrgSalesOrganizationCode(batchUpdateLineStatusRequst.getBizId());
                    break;
                case BUSINESS_UNIT:
                    queryRequest.setOrgBusinessUnitCode(batchUpdateLineStatusRequst.getBizId());
                    break;
                default:
            }
        }
        queryRequest.setField("id");
        queryRequest.setAsc(true);
        return queryRequest;
    }

    private Boolean checkStatus(SalesPlanLineSDO sdo) {
        // 月度计划量为0,说明上中下旬都没有填，判断为该明细为完成填写
        return sdo.getMonthCount() != null && sdo.getMonthFirstCount() != null
                && sdo.getMonthMiddleCount() != null && sdo.getMonthLastCount() != null;
    }

}
